<template>
	<!-- 微信授权登录 -->
	<view class="container">
		<view class="wechatapp">
			<view class="header">
				<image class="image" mode="aspectFill" :src="storeInfo && storeInfo.image_url ? 
								storeInfo.image_url : '/static/default-avatar.png'"></image>
			</view>
		</view>

		<view style="text-align: center;">+
		
			<view class="auth-title">需要您提供以下信息</view>
			<view class="auth-subtitle">用于获得你的公开信息（昵称、头像等）</view>
		</view>
		
		<view class="login-btn">
			<!-- 获取微信用户信息 -->
			<button class="button btn-normal" @click.stop="getUserProfile">授权登录</button>
		</view>
		<view class="no-login-btn">
			<button class="button btn-normal" @click="handleCancel">暂不登录</button>
		</view>

	</view>
</template>

<script>
	import store from '@/store'
	import { isEmpty } from '@/utils/util'
	import SettingModel from '@/common/model/Setting'

	export default {
		data() {
			return {
				// 商城基本信息
				storeInfo: undefined,
				// 微信小程序登录凭证 (code)
				// 提交到后端，用于换取openid
				code: ''
			}
		},
		created() {
			// 获取商城信息
			this.getStoreInfo()
		},
		methods: {
			// 获取商城信息
			getStoreInfo() {
				SettingModel.item('store').then(store => {
					console.log('获取商城信息==>', store);
					this.storeInfo = store
				})
			},

			// 获取code
			getCode() {
				const that = this
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success(res) {
							that.code = res.code
							console.log('获取微信code成功==>', res.code);
							resolve(res.code)
						},
						fail() {
							reject()
						}
					})
				})
			},

			// 获取微信用户信息
			getUserProfile() {
				const that = this
        // wx.canIUse()方法判断小程序的Api、组件参数回调是否可用
				wx.canIUse('getUserProfile') && wx.getUserProfile({
					lang: 'zh_CN',
					desc: '获取用户相关信息',
					success({ userInfo }) {
						console.log('getUserProfile获取微信用户信息成功==>', userInfo);
						// 授权成功
						that.onAuthSuccess(userInfo)
					},
					fail() {
						console.log('用户拒绝授权');
					}
				})
			},

			// 授权成功事件
			// 这里分为两个逻辑:
			// 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
			// 2.如果不存在该用户, 则显示注册页面, 需填写手机号
			// 3.如果后端报错了, 则显示错误信息(报错原因，后端无该用户，所以需要先登录)
			async onAuthSuccess(userInfo) {
				const that = this
				// 提交到后端
				store.dispatch('LoginMpWx', {
						partyData: {
							code: await that.getCode(),
							oauth: 'MP-WEIXIN',
							userInfo
						},
						refereeId: store.getters.refereeId
					})
					.then(res => {
						// 微信授权一键登录成功
						that.$toast(res.message)
						console.log('微信授权一键登录成功==>', res);
						// 跳转回原界面
						setTimeout(() => {
							that.onNvigateBack()
						}, 2000)
					})
					.catch(err => {
						const resultData = err.result.data
						console.log('微信授权一键登录失败==>', err);
						// 显示错误信息
						if (isEmpty(resultData)) {
							that.$toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							setTimeout(() => that.onNvigateBack(1), 2000)
						}
						// 判断还需绑定手机
						if (resultData.isBindMobile) {
							that.onEmitSuccess(userInfo)
						}
					})
			},

			// 将oauth提交给父级
			// 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
			async onEmitSuccess(userInfo) {
				const that = this
				this.$emit('success', {
					// 第三方登录类型
					oauth: 'MP-WEIXIN',
					// 微信登录的code，用户换取openid
					code: await that.getCode(),
					// 微信用户信息
					userInfo
				})
			},
			
			// 暂不登录
			handleCancel() {
				this.onNvigateBack()
			},

			// 登录成功，跳转回原页面
			onNvigateBack(delta) {
				const pages = getCurrentPages()
				if (pages.length > 1) {
					uni.navigateBack({
						delta: Number(delta || 1)
					})
				} else {
					this.$navTo('pages/index/index')
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 60rpx;
		font-size: 32rpx;
		background: #fff;
		min-height: 100vh;
		// text-align: center;
	}

	.wechatapp {
		padding: 80rpx 0 48rpx;
		border-bottom: 1rpx solid #e3e3e3;
		margin-bottom: 72rpx;
		text-align: center;

		.header {
			width: 190rpx;
			height: 190rpx;
			border: 4rpx solid #fff;
			margin: 0 auto 0;
			border-radius: 50%;
			overflow: hidden;
			box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);

			.image {
				display: block;
				width: 100%;
				height: 100%;
			}
		}
	}

	.auth-title {
		color: #585858;
		font-size: 32rpx;
		margin-bottom: 50rpx;
	}

	.auth-subtitle {
		color: #888;
		margin-bottom: 88rpx;
		font-size: 25rpx;
	}

	.login-btn {
		padding: 0 20rpx;

		.button {
			height: 88rpx;
			background: linear-gradient(to right, #ecb53c, #ff9211);
			color: #fff;
			font-size: 30rpx;
			border-radius: 999rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}


	.no-login-btn {
		margin-top: 20rpx;
		padding: 0 20rpx;

		.button {
			height: 88rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			border-radius: 999rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>
